<template>
	<div v-if="!props.isDisabled" style="display: flex; justify-content: flex-end">
		<el-button type="primary" @click="handleAddUnit(0)">新增</el-button>
	</div>
	<el-table v-loading="state1.dataListLoading" :data="state1.dataList" stripe class="layout-table">
		<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
		<el-table-column prop="editorUnitName" label="主编单位" header-align="center" align="center"></el-table-column>
		<el-table-column prop="contacts" label="联系人" header-align="center" align="center"></el-table-column>
		<el-table-column prop="contactsTel" label="联系人电话" header-align="center" align="center"></el-table-column>
		<el-table-column prop="responsiblePerson" label="负责人" header-align="center" align="center"></el-table-column>
		<el-table-column prop="responsiblePersonTel" label="负责人电话" header-align="center" align="center"></el-table-column>
		<!-- <el-table-column prop="userCode" label="是否发布" header-align="center" align="center">
			<template #default="scope">
				{{ scope.row.isPublish === 1 ? '是' : '否' }}
			</template>
		</el-table-column> -->
		<el-table-column v-if="!props.isDisabled" label="操作" fixed="right" header-align="center" align="center" width="150">
			<template #default="scope">
				<el-icon :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="handleEditUnit(0, scope.row)">
					<Edit />
				</el-icon>
				<el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="handleDeleteUnit(0, scope.row)">
					<Delete />
				</el-icon>
			</template>
		</el-table-column>
	</el-table>
	<div v-if="!props.isDisabled" style="display: flex; justify-content: flex-end; margin-top: 20px">
		<el-button type="primary" @click="handleAddUnit(1)">新增</el-button>
	</div>
	<el-table v-loading="state2.dataListLoading" :data="state2.dataList" stripe class="layout-table">
		<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
		<el-table-column prop="editorUnitName" label="参编单位" header-align="center" align="center"></el-table-column>
		<el-table-column prop="contacts" label="联系人" header-align="center" align="center"></el-table-column>
		<el-table-column prop="contactsTel" label="联系人电话" header-align="center" align="center"></el-table-column>
		<el-table-column prop="responsiblePerson" label="负责人" header-align="center" align="center"></el-table-column>
		<el-table-column prop="responsiblePersonTel" label="负责人电话" header-align="center" align="center"></el-table-column>
		<!-- <el-table-column prop="userCode" label="是否发布" header-align="center" align="center">
			<template #default="scope">
				{{ scope.row.isPublish === 1 ? '是' : '否' }}
			</template>
		</el-table-column> -->
		<el-table-column v-if="!props.isDisabled" label="操作" fixed="right" header-align="center" align="center" width="150">
			<template #default="scope">
				<el-icon :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="handleEditUnit(1, scope.row)">
					<Edit />
				</el-icon>
				<el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="handleDeleteUnit(1, scope.row)">
					<Delete />
				</el-icon>
			</template>
		</el-table-column>
	</el-table>
	<cmDialog v-model="dialogState" :modal-title="unitType == 0 ? '主编单位' : '参编单位'" model-width="1000px">
		<div style="padding: 20px 40px">
			<el-form ref="unitFormRef" :model="unitForm" :rules="unitRules" label-width="180px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="次序" prop="orderName">
							<el-input v-model="unitForm.orderName" type="number" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="单位名称" prop="editorUnitName">
							<el-input v-model="unitForm.editorUnitName" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系人" prop="contacts">
							<el-input v-model="unitForm.contacts" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="联系电话(手机)" prop="contactsTel">
							<el-input v-model="unitForm.contactsTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系人邮箱" prop="contactsEmail">
							<el-input v-model="unitForm.contactsEmail" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="联系地址" prop="contactsAddress">
							<el-input v-model="unitForm.contactsAddress" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="负责人" prop="responsiblePerson">
							<el-input v-model="unitForm.responsiblePerson" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="负责人电话(手机或座机)" prop="responsiblePersonTel">
							<el-input v-model="unitForm.responsiblePersonTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="负责人邮箱" prop="responsiblePersonEmail">
							<el-input v-model="unitForm.responsiblePersonEmail" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="企业社会信用代码" prop="userCode">
							<el-input v-model="unitForm.userCode" placeholder="请输入" @input="handleCreditCodeInput" />
						</el-form-item>
					</el-col>
					<!-- <el-col :span="12">
						<el-form-item label="是否发布" prop="isPublish">
							<el-radio-group v-model="unitForm.isPublish">
								<el-radio :value="1">是</el-radio>
								<el-radio :value="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col> -->
					<el-col :span="12">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="unitForm.remark" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialog-foot">
				<el-button @click="handleAddCancel">取消</el-button>
				<el-button type="primary" @click="handleAddUnitFormSubmit(unitFormRef)">确定</el-button>
			</div>
		</div>
	</cmDialog>
</template>
<script setup lang="ts">
import { editorUnitDelApi, editorUnitListApi, editorUnitUpdateApi } from '@/api/standard/maintenance/index'
import cmDialog from '@/components/cm-dialog/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { reactive, ref, watch } from 'vue'

const props = defineProps({
	systemId: {
		type: String,
		default: ''
	},
	currentTab: {
		type: String,
		default: ''
	},
	projectId: {
		type: String,
		default: ''
	},
	isDisabled: {
		type: Boolean,
		default: false
	}
})

const state1 = reactive({
	pageNum: 1,
	pageSize: 100,
	total: 1,
	dataListLoading: false,
	dataList: []
})

const state2 = reactive({
	pageNum: 1,
	pageSize: 100,
	total: 1,
	dataListLoading: false,
	dataList: []
})
const dialogState = ref(false)
const unitType = ref(0)
const unitFormRef = ref<FormInstance>()
const unitForm = reactive({
	orderName: 1,
	editorUnitName: '',
	contacts: '',
	contactsTel: '',
	contactsEmail: '',
	contactsAddress: '',
	responsiblePerson: '',
	responsiblePersonTel: '',
	responsiblePersonEmail: '',
	userCode: '',
	isPublish: 0,
	remark: ''
})

const phoneOrLandlineValidator = (rule, value, callback) => {
	const phoneRegex = /^1[3-9]\d{9}$/
	const landlineRegex = /^(0\d{2,3})-?\d{7,8}$/

	if (!phoneRegex.test(value) && !landlineRegex.test(value)) {
		callback(new Error('请输入有效的手机号或座机号码'))
	} else {
		callback()
	}
}

const validateCreditCode = (rule: any, value: string, callback: (error?: Error) => void) => {
	if (!value) {
		callback(new Error('请输入社会信用代码'))
		return
	}

	// 1. 格式校验
	if (!/^[0-9A-Z]{18}$/.test(value)) {
		callback(new Error('必须为18位数字或大写字母'))
		return
	}
	callback()
}

const unitRules = reactive<FormRules>({
	orderName: [{ required: true, message: '请输入', trigger: 'blur' }],
	editorUnitName: [{ required: true, message: '请输入', trigger: 'blur' }],
	contacts: [{ required: true, message: '请输入', trigger: 'blur' }],
	userCode: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ validator: validateCreditCode, trigger: 'blur' }
	],
	contactsTel: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
	],
	contactsEmail: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
			message: '请输入有效的邮箱地址',
			trigger: 'blur'
		}
	],
	contactsAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
	responsiblePerson: [{ required: true, message: '请输入', trigger: 'blur' }],
	responsiblePersonTel: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ validator: phoneOrLandlineValidator, trigger: 'blur' }
	],
	responsiblePersonEmail: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
			message: '请输入有效的邮箱地址',
			trigger: 'blur'
		}
	]
})

watch(
	() => props.currentTab,
	val => {
		if (val && val == 'tab2') {
			getDataList1()
			getDataList2()
		}
	}
)

watch(
	() => dialogState.value,
	val => {
		if (!val) {
			restForm()
		}
	}
)

const handleCreditCodeInput = (value: string) => {
	unitForm.userCode = value.toUpperCase()
}

const getDataList1 = () => {
	state1.dataListLoading = true
	editorUnitListApi({
		systemId: props.systemId,
		unitType: 0,
		pageNum: state1.pageNum,
		pageSize: state1.pageSize
	}).then(res => {
		state1.dataListLoading = false
		state1.dataList = res.data.list || []
		state1.total = res.data.total || 0
	})
}

const getDataList2 = () => {
	state2.dataListLoading = true
	editorUnitListApi({
		systemId: props.systemId,
		unitType: 1,
		pageNum: state2.pageNum,
		pageSize: state2.pageSize
	}).then(res => {
		state2.dataListLoading = false
		state2.dataList = res.data.list || []
		state2.total = res.data.total || 0
	})
}

const handleAddUnit = (type: number) => {
	unitType.value = type
	if (type == 0) {
		unitForm.orderName = state1.dataList.length + 1
	} else {
		unitForm.orderName = state2.dataList.length + 1
	}
	dialogState.value = true
}

const restForm = () => {
	Object.assign(unitForm, { id: '' })
	Object.assign(unitForm, { orderName: 1 })
	Object.assign(unitForm, { editorUnitName: '' })
	Object.assign(unitForm, { contacts: '' })
	Object.assign(unitForm, { contactsTel: '' })
	Object.assign(unitForm, { contactsEmail: '' })
	Object.assign(unitForm, { contactsAddress: '' })
	Object.assign(unitForm, { responsiblePerson: '' })
	Object.assign(unitForm, { responsiblePersonTel: '' })
	Object.assign(unitForm, { responsiblePersonEmail: '' })
	Object.assign(unitForm, { remark: '' })
	Object.assign(unitForm, { userCode: '' })
}

const handleAddCancel = () => {
	restForm()
	dialogState.value = false
}

const handleAddUnitFormSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			let submittedData = { ...unitForm, systemId: props.systemId, projectInfoId: props.projectId }
			editorUnitUpdateApi(unitType.value, submittedData).then(res => {
				unitType.value == 0 ? getDataList1() : getDataList2()
				handleAddCancel()
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}

const handleEditUnit = (type: number, row: any) => {
	unitType.value = type
	Object.assign(unitForm, row)
	dialogState.value = true
}

const handleDeleteUnit = (type: number, row: any) => {
	ElMessageBox.confirm('确定要删除吗?', '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		unitType.value = type
		editorUnitDelApi({
			id: row.id
		}).then(() => {
			unitType.value == 0 ? getDataList1() : getDataList2()
		})
	})
}
</script>
<style lang="scss" scoped>
.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}
</style>
